package com.example.authservice.controller;

import com.example.api.service.AuthService;
import com.example.api.service.OpenApiAppService;
import com.example.common.constant.ApiParamConsts;
import com.example.common.core.AjaxResult;
import com.example.common.entity.OpenApiApp;
import com.example.common.entity.vo.AppInfoVO;
import com.example.common.exception.BaseException;
import com.example.common.exception.ExceptionCode;
import com.example.common.mapper.OpenApiAppMapper;
import com.example.common.utils.WillingAESUtils;
import lombok.SneakyThrows;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * 认证控制api
 *
 * @author Destinycc
 */
@RequestMapping("/access_token")
@RestController
public class AccessTokenController {

    @Reference
    AuthService authService;

    @Reference
    OpenApiAppService openApiAppService;

    /**
     * 获取accessToken接口
     * @param
     * @return
     */
//    @SentinelResource(value = "get-token-limit", blockHandler = "handleBlock")
    @GetMapping("/get")
    @SneakyThrows
    public AjaxResult getAccessToken(@RequestParam(value = ApiParamConsts.APP_ID) String appId,
                                     @RequestParam(value = ApiParamConsts.APP_SECRET) String appSecret,
                                     @RequestParam(value = ApiParamConsts.FORCE_REFRESH, required = false) Boolean forceRefresh) {
        AppInfoVO appInfo = new AppInfoVO(appId, appSecret);
        if (forceRefresh == null) {
            forceRefresh = false;
        }
        OpenApiApp openApiApp = openApiAppService.getAppByAppIdAndSecret(appId, WillingAESUtils.encrypt(appSecret));
        if (openApiApp == null){
            throw new BaseException(ExceptionCode.PARAM_NOT_VALID, "app_id或app_secret不合法");
        }
        String tenantId = String.valueOf(openApiApp.getId());
        return AjaxResult.success(authService.genAccessToken(appInfo, tenantId, forceRefresh));
    }

//    public AjaxResult handleBlock(@RequestBody AppInfoVO appInfoVO,
//                                  BlockException e){
//        return AjaxResult.success("请求上限");
//    }
}
